
#import "XmlRpcRequest.h"

@implementation XmlRpcRequest

//
// encoder
//
@synthesize encoder															= _encoder;

//
// result
//
@synthesize result															= _result;

//
// init with method name
//
- (id)initWithMethod:(NSString*)methodName
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	//
	// setup encoder/decoder
	//
	self.encoder															= [[[XmlRpcEncoder alloc] init] autorelease];
	self.encoder.methodName													= methodName;
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.encoder															= nil;
	self.result																= nil;
	
	[super dealloc];
}

//
// add parameter
//
- (void)addParameter:(id)parameter
{
	[self.encoder.parameterList addObject:parameter];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// call super
	//
	[super setupRequest];
	
	//
	// setup post data
	//
	self.postData															= [[self.encoder encode] dataUsingEncoding:NSUTF8StringEncoding];
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	if(self.response.statusCode == 200)
	{
		//
		// decode result
		//
		BOOL isFault														= NO;
		self.result															= [XmlRpcDecoder decodeData:self.dataBuffer isFault:&isFault];
		if(isFault)
			[self checkFaultDictionary:self.result];
	}
	
	[super connectionDidFinishLoading:connection];
}

//
// check fault dictionary
//
- (NSError*)checkFaultDictionary:(id)fault
{
	if([fault isKindOfClass:[NSDictionary class]])
	{
		id code																= [fault valueForKey:@"faultCode"];
		id reason															= [fault valueForKey:@"faultString"];
		if(code || reason)
		{
			if(!reason)
				reason														= [NSString stringWithFormat:@"Fault error:%@", code];
			
			[self setErrorMessage:reason code:[code integerValue] domain:@"XmlRpcErrorDomain"];
			self.result														= nil;
		}
	}
	
	return self.error;
}

@end
